<template>
  <div class="profile">
    <SideNav />
    <div class="main-content">
      <!-- 加载动画 -->
      <div class="loading-overlay" v-if="loading">
        <div class="loading-spinner">
          <i class="fas fa-spinner fa-spin"></i>
          <div class="loading-text">加载中...</div>
        </div>
      </div>

      <!-- 个人信息卡片 -->
      <div class="profile-header" v-if="!loading">
        <div class="profile-card">
          <div class="profile-avatar">
            <img :src="userInfo.headPictureUrl" alt="用户头像">
            <div class="edit-avatar" @click="triggerAvatarUpload">
              <i class="fas fa-camera"></i>
            </div>
            <input 
              type="file" 
              ref="avatarInput"
              @change="handleAvatarChange" 
              accept="image/*"
              class="hidden"
            >
          </div>
          <div class="profile-info">
            <h2>{{ userInfo.userName }}</h2>
            <div class="user-meta">
              <span class="meta-item">
                <i class="fas fa-birthday-cake"></i>
                {{ userInfo.age }}岁
              </span>
              <span class="meta-item">
                <i class="fas fa-venus-mars"></i>
                {{ userInfo.sex }}
              </span>
            </div>
            <p class="bio">{{ userInfo.introduction || '这个人很懒，什么都没有写~' }}</p>
            <div class="stats">
              <div class="stat-item">
                <span class="number">{{ userStats.solvedCount }}</span>
                <span class="label">解题数</span>
              </div>
              <div class="stat-item">
                <span class="number">{{ userStats.maxConsecutiveDays }}</span>
                <span class="label">最大连续做题</span>
              </div>
            </div>
          </div>
          <button class="edit-profile" @click="showEditProfileDialog">
            <i class="fas fa-edit"></i>
            编辑资料
          </button>
        </div>
      </div>

      <!-- 详细信息区域 -->
      <div class="profile-details" v-if="!loading">
        <!-- 左侧信息 -->
        <div class="left-section">
          <!-- 最近提交 -->
          <div class="section-card">
            <h3><i class="fas fa-history"></i> 最近提交</h3>
            <div class="submission-list">
              <div class="submission-item" v-for="submission in submissions" :key="submission.created_at">
                <span class="status" :style="{'background-color': submissionStatusColors[submission.status]}">
                  <i :class="submission.status === 'Accepted' ? 'fas fa-check' : 'fas fa-times'"></i>
                </span>
                <div class="submission-info">
                  <span class="problem-name">{{ submission.title }}</span>
                  <span class="difficulty-tag" :style="{'background-color': difficultyColors[submission.difficulty]}">
                    {{ submission.difficulty }}
                  </span>
                </div>
                <span class="time">{{ formatSubmissionTime(submission.created_at) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧信息 -->
        <div class="right-section">
          <!-- 能力分析 -->
          <div class="section">
            <h3>能力分析</h3>
            <div class="skills-list">
              <div class="skill-item" v-for="(skill, index) in skills" :key="index">
                <div class="skill-info">
                  <span class="skill-name">{{skill.name}}</span>
                  <span class="skill-value">{{skill.value}} 题</span>
                </div>
                <div class="skill-bar">
                  <div class="skill-progress" :style="{width: calculateProgressWidth(skill.value) + '%'}"></div>
                </div>
              </div>
            </div>
          </div>

          <!-- 学习日历 -->
          <div class="section-card">
            <h3><i class="fas fa-calendar-alt"></i> 学习日历</h3>
            <div class="calendar-container">
              <v-chart class="calendar-chart" :option="calendarOption" autoresize />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑资料弹窗 -->
    <div class="dialog-overlay" v-if="showEditDialog" @click="showEditDialog = false">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h2><i class="fas fa-user-edit"></i> 编辑个人资料</h2>
          <button class="close-btn" @click="showEditDialog = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <form @submit.prevent="updateProfile" class="edit-profile-form">
            <!-- 基本信息部分 -->
            <div class="form-section">
              <h3>基本信息</h3>
              <div class="form-row">
                <div class="form-group">
                  <label><i class="fas fa-user"></i> 用户名</label>
                  <input 
                    type="text" 
                    v-model="editForm.username"
                    placeholder="请输入用户名"
                    required
                  >
                </div>
                <div class="form-group">
                  <label><i class="fas fa-venus-mars"></i> 性别</label>
                  <select v-model="editForm.sex" required>
                    <option value="男">男</option>
                    <option value="女">女</option>
                  </select>
                </div>
              </div>
              
              <div class="form-group">
                <label><i class="fas fa-birthday-cake"></i> 生日</label>
                <input 
                  type="date" 
                  v-model="editForm.birth"
                  required
                >
              </div>
            </div>

            <!-- 个人简介部分 -->
            <div class="form-section">
              <h3>个人简介</h3>
              <div class="form-group">
                <textarea 
                  v-model="editForm.bio"
                  placeholder="介绍一下自己吧..."
                  rows="4"
                ></textarea>
              </div>
            </div>

            <!-- 账户安全部分 -->
            <div class="form-section">
              <h3>账户安全</h3>
              <button type="button" class="change-password-btn" @click="showPasswordDialog = true">
                <i class="fas fa-key"></i>
                修改密码
              </button>
            </div>

            <!-- 操作按钮 -->
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="showEditDialog = false">
                <i class="fas fa-times"></i> 取消
              </button>
              <button type="submit" class="submit-btn">
                <i class="fas fa-check"></i> 保存修改
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <div class="dialog-overlay" v-if="showPasswordDialog" @click="showPasswordDialog = false">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h2><i class="fas fa-key"></i> 修改密码</h2>
          <button class="close-btn" @click="showPasswordDialog = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <form @submit.prevent="updatePassword" class="password-form">
            <div class="form-group">
              <label><i class="fas fa-lock"></i> 当前密码</label>
              <input 
                type="password" 
                v-model="passwordForm.currentPassword"
                placeholder="请输入当前密码"
                required
              >
            </div>
            <div class="form-group">
              <label><i class="fas fa-key"></i> 新密码</label>
              <input 
                type="password" 
                v-model="passwordForm.newPassword"
                placeholder="请输入新密码"
                required
              >
            </div>
            <div class="form-group">
              <label><i class="fas fa-check-circle"></i> 确认新密码</label>
              <input 
                type="password" 
                v-model="passwordForm.confirmPassword"
                placeholder="请再次输入新密码"
                required
              >
            </div>
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="showPasswordDialog = false">
                <i class="fas fa-times"></i> 取消
              </button>
              <button type="submit" class="submit-btn">
                <i class="fas fa-check"></i> 确认修改
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
    <MessagePopup
      :visible.sync="messageVisible"
      :type="messageType"
      :message="messageText"
      :duration="2000"
    />
  </div>
</template>

<script>
import SideNav from '@/components/SideNav.vue'
import axios from 'axios'
import { baseURL } from '@/utils/api'
import { mapActions} from 'vuex';
import MessagePopup from '@/components/MessagePopup.vue'
import md5 from 'js-md5'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { HeatmapChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  VisualMapComponent,
  CalendarComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

// 注册ECharts组件
use([
  CanvasRenderer,
  HeatmapChart,
  TitleComponent,
  TooltipComponent,
  VisualMapComponent,
  CalendarComponent
])

export default {
  name: 'ProfileView',
  components: {
    SideNav,
    MessagePopup,
    VChart
  },
  data() {
    const today = new Date();
    const startDate = new Date();
    startDate.setDate(today.getDate() - 89); // 获取90天前的日期
    
    return {
      skills: [
        { name: '简单', value: 0 },
        { name: '中等', value: 0 },
        { name: '困难', value: 0 }
      ],
      showEditDialog: false,
      showPasswordDialog: false,
      userAvatar: '@/assets/QQ.png',
      editForm: {
        username: '',
        bio: '',
        email: '',
        birth: '',
        sex: ''
      },
      passwordForm: {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      // 初始化用户信息，设置默认值
      userInfo: {
        userId: '',
        userName: '',
        age: '',
        sex: '',
        introduction: '',
        headPictureUrl: ''
      },
      messageVisible: false,
      messageType: 'info', // 设置默认值为 'info'
      messageText: '',
      // 添加提交记录相关数据
      submissions: [],
      submissionStatusColors: {
        'Accepted': '#42b983',
        'Wrong Answer': '#ff4757',
        'Time Limit Exceeded': '#ffa502',
        'Runtime Error': '#ff6b81',
        'Compilation Error': '#747d8c'
      },
      difficultyColors: {
        'EASY': '#42b983',
        'MEDIUM': '#ffa502',
        'HARD': '#ff4757'
      },
      userStats: {
        solvedCount: 0,
        maxConsecutiveDays: 0
      },
      // 添加日历数据
      activityData: [],
      calendarOption: {
        tooltip: {
          position: 'top',
          formatter: function (p) {
            return `${p.data[0]}: ${p.data[1]} 次提交`
          }
        },
        visualMap: {
          min: 0,
          max: 10,
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: 0,
          inRange: {
            color: ['#e8f4ff', '#3498db']
          }
        },
        calendar: {
          top: 30,
          left: 30,
          right: 5,
          cellSize: ['auto', 12],
          range: [
            startDate.toISOString().split('T')[0], 
            today.toISOString().split('T')[0]
          ],
          itemStyle: {
            borderWidth: 0.5
          },
          yearLabel: { show: false }
        },
        series: [{
          type: 'heatmap',
          coordinateSystem: 'calendar',
          data: []
        }]
      },
      loading: true
    }
  },
  computed:{
    // 删除 userId computed 属性
  },
  methods: {
    // 删除 mapActions
    // ...mapActions('userAbout', ['adduser']),

    //显示消息
    showMessage(type, text) {
      // 确保类型有效
      const validTypes = ['success', 'error', 'warning', 'info'];
      this.messageType = validTypes.includes(type) ? type : 'info';
      this.messageText = text;
      this.messageVisible = true;
    },
    showEditProfileDialog() {
      this.editForm = {
        username: this.userInfo.userName,
        bio: this.userInfo.introduction || '',
        sex: this.userInfo.sex,
        birth: this.formatDate(this.userInfo.birth) || '',
      }
      this.showEditDialog = true
    },
    triggerAvatarUpload() {
      this.$refs.avatarInput.click()
    },
    async handleAvatarChange(event) {
      const file = event.target.files[0];
      if (!file) return;

      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        this.showMessage('error', '请选择图片文件');
        return;
      }

      // 验证文件大小（例如限制为 2MB）
      const maxSize = 2 * 1024 * 1024;
      if (file.size > maxSize) {
        this.showMessage('error', '图片大小不能超过 2MB');
        return;
      }

      try {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('token', localStorage.getItem('token'));
        formData.append('user_id', localStorage.getItem('userId')); // 从 localStorage 获取

        const response = await axios({
          method: 'put',
          url: baseURL + '/user-service/user/updateUserInfos_headpicture_url',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        if (response.data.result === 'success') {
          this.userInfo.headPictureUrl = response.data.userInfos.user_headpicture_url;
          this.showMessage('success', '头像更新成功');
          
          const userInfos = response.data.userInfos;
          this.userInfo = {
            ...this.userInfo,
            headPictureUrl: userInfos.user_headpicture_url
          };
        } else {
          this.showMessage('error', '头像更新失败：' + response.data.message);
        }
      } catch (error) {
        console.error('上传头像失败:', error);
        this.showMessage('error', '上传头像失败，请稍后重试');
      }

      event.target.value = '';
    },
    async updateProfile() {
      try {
        // 构造请求数据
        const userInfos = {
          user_id: this.userInfo.userId,
          user_name: this.editForm.username,
          user_sex: this.editForm.sex,
          user_birth: this.editForm.birth,
          user_introduction: this.editForm.bio
        };

        // 发送请求
        const response = await axios({
          method: 'post',
          url: baseURL + '/user-service/user/updateUserInfos',
          data: userInfos,
          params: {
            token: localStorage.getItem('token')
          }
        });

        console.log(response.data);
        if (response.data.result === 'success') {
          // 显示成功消息
          this.showMessage('success', '个人资料更新成功');
          
          // 关闭编辑弹窗
          this.showEditDialog = false;
          
          // 更新本地用户信息
          const userInfos = response.data.userInfos;
          this.userInfo = {
            userId: userInfos.user_id,
            userName: userInfos.user_name,
            age: this.calculateAge(userInfos.user_birth),
            sex: userInfos.user_sex,
            introduction: userInfos.user_introduction,
            headPictureUrl: userInfos.user_headpicture_url || this.userAvatar
          };
        } else {
          // 显示错误消息
          this.showMessage('error', '更新失败：' + response.data.message);
        }
      } catch (error) {
        console.error('更新个人资料失败:', error);
        this.showMessage('error', '更新失败，请稍后重试');
      }
    },
    async updatePassword() {
      try {
        // 表单验证
        if (!this.passwordForm.currentPassword || !this.passwordForm.newPassword || !this.passwordForm.confirmPassword) {
          this.showMessage('error', '请填写所有密码字段');
          return;
        }

        if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
          this.showMessage('error', '两次输入的新密码不一致');
          return;
        }

        if (this.passwordForm.newPassword === this.passwordForm.currentPassword) {
          this.showMessage('error', '新密码不能与当前密码相同');
          return;
        }

        // 发送修改密码请求
        const response = await axios({
          method: 'put',
          url: baseURL + '/user-service/user/updateUser_password',
          params: {
            user_id: localStorage.getItem('userId'),
            account: localStorage.getItem('userAccount'),
            old_password: md5(this.passwordForm.currentPassword),
            user_password: md5(this.passwordForm.newPassword),
            token: localStorage.getItem('token')
          }
        });

        if (response.data.result === 'success') {
          // 先关闭密码修改弹窗
          this.showPasswordDialog = false;
          
          // 清空表单
          this.passwordForm = {
            currentPassword: '',
            newPassword: '',
            confirmPassword: ''
          };

          // 显示成功消息
          this.showMessage('success', '密码修改成功');
          
          // 等待成功消息显示完毕后再显示提示重新登录的消息
          setTimeout(() => {
            this.showMessage('info', '请使用新密码重新登录');
            
            // 等待提示消息显示后再清除登录信息并跳转
            setTimeout(() => {
              // 清除登录信息
              localStorage.removeItem('token');
              localStorage.removeItem('userId');
              localStorage.removeItem('userAccount');
              localStorage.removeItem('userPassword');
              
              // 跳转到登录页
              this.$router.push('/');
            }, 1500);
          }, 1500);
        } else {
          // 显示错误信息
          this.showMessage('error', response.data.message || '密码修改失败');
        }
      } catch (error) {
        console.error('修改密码失败:', error);
        this.showMessage('error', '修改密码失败，请稍后重试');
      }
    },
    calculateAge(birthDate) {
      const birth = new Date(birthDate);
      const today = new Date();
      let age = today.getFullYear() - birth.getFullYear();
      const monthDiff = today.getMonth() - birth.getMonth();
      
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
        age--;
      }
      return age;
    },
    async fetchUserInfo() {
      this.loading = true; // 开始加载时设置loading为true
      try {
        const response = await axios({
          method: 'get',
          url: baseURL + '/user-service/user/getUserInfos',
          params: {
            user_id: localStorage.getItem('userId'),
            token: localStorage.getItem('token')
          }
        });
        
        if (response.data.result === 'success') {
          const userInfos = response.data.userInfos;
          const newUserInfo = {
            userId: userInfos.user_id,
            userName: userInfos.user_name,
            age: this.calculateAge(userInfos.user_birth),
            sex: userInfos.user_sex,
            introduction: userInfos.user_introduction,
            headPictureUrl: userInfos.user_headpicture_url || this.userAvatar
          };
          
          this.userInfo = newUserInfo;
          this.userStats.solvedCount = userInfos.user_solved_count;
          return Promise.resolve(); // 明确返回已解决的Promise
        } else {
          // token 可能过期
          if (response.data.message?.includes('Token验证失败')) {
            this.showMessage('error', 'Token已过期，请重新登录');
            // 清除认证信息
            localStorage.removeItem('token');
            localStorage.removeItem('userId');
            // 跳转到登录页
            this.$router.push('/login');
          } else {
            this.showMessage('error', '获取用户信息失败');
          }
          return Promise.reject(new Error(response.data.message || '获取用户信息失败')); // 返回被拒绝的Promise
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        this.showMessage('error', '获取用户信息失败，请稍后重试');
        return Promise.reject(error); // 返回被拒绝的Promise
      }
    },
    // 格式化日期为 YYYY-MM-DD 格式
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 修改获取提交记录的方法
    async fetchSubmissions() {
      try {
        const userId = localStorage.getItem('userId');
        if (!userId) {
          this.showMessage('error', '用户未登录');
          return;
        }

        const response = await axios({
          method: 'get',
          url: baseURL + `/CodeQuestion-service/problems/getSubmissionByUserId/${userId}`
        });

        if (response.data.result === 'success') {
          this.submissions = response.data.recentSubmissions;
        } else {
          this.showMessage('error', '获取提交记录失败：' + response.data.message);
        }
      } catch (error) {
        console.error('获取提交记录失败:', error);
        this.showMessage('error', '获取提交记录失败，请稍后重试');
      }
    },
    // 添加格式化时间的方法
    formatSubmissionTime(dateTime) {
      const now = new Date();
      const submissionDate = new Date(dateTime);
      const diffInMinutes = Math.floor((now - submissionDate) / (1000 * 60));

      if (diffInMinutes < 1) return '刚刚';
      if (diffInMinutes < 60) return `${diffInMinutes}分钟前`;
      
      const diffInHours = Math.floor(diffInMinutes / 60);
      if (diffInHours < 24) return `${diffInHours}小时前`;
      
      const diffInDays = Math.floor(diffInHours / 24);
      if (diffInDays < 30) return `${diffInDays}天前`;
      
      return submissionDate.toLocaleDateString();
    },
    // 获取过去N天的日期范围
    getLastNDays(n) {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * (n - 1))
      return [start.toISOString().split('T')[0], end.toISOString().split('T')[0]]
    },
    
    // 获取用户活动历史
    async fetchUserActivityHistory() {
      try {
        const userId = localStorage.getItem('userId');
        if (!userId) {
          this.showMessage('error', '用户未登录');
          return;
        }

        const response = await axios({
          method: 'get',
          url: baseURL + `/CodeQuestion-service/problems/getUserActivityHistory/${userId}`
        });

        if (response.data.result === 'success') {
          // 将活动数据转换为ECharts需要的格式 [日期, 数量]
          this.activityData = response.data.activities.map(item => [
            item.date, 
            item.count
          ]);
          
          // 更新日历图表
          this.calendarOption.series[0].data = this.activityData;
          this.calendarOption.visualMap.max = Math.max(
            ...this.activityData.map(item => item[1]), 
            5  // 至少为5，避免没有数据时显示异常
          );
          
          // 计算最大连续做题天数
          this.calculateMaxConsecutiveDays();
        } else {
          console.error('获取用户活动历史失败：', response.data.message);
        }
      } catch (error) {
        console.error('获取用户活动历史失败:', error);
      }
    },
    // 计算最大连续做题天数
    calculateMaxConsecutiveDays() {
      if (!this.activityData || this.activityData.length === 0) {
        this.userStats.maxConsecutiveDays = 0;
        return;
      }
      
      // 将活动数据转换为日期和次数的映射
      const activityMap = new Map();
      this.activityData.forEach(([date, count]) => {
        activityMap.set(date, count);
      });
      
      // 按日期排序
      const dates = [...activityMap.keys()].sort();
      
      let maxConsecutive = 0;
      let currentConsecutive = 0;
      let previousDate = null;
      
      // 遍历排序后的日期
      for (const date of dates) {
        const count = activityMap.get(date);
        const currentDate = new Date(date);
        
        // 如果当天有提交记录
        if (count > 0) {
          // 第一次遍历或与前一天相连
          if (previousDate === null) {
            currentConsecutive = 1;
          } else {
            const diffDays = Math.round((currentDate - previousDate) / (1000 * 60 * 60 * 24));
            
            // 如果是连续的一天
            if (diffDays === 1) {
              currentConsecutive++;
            } else {
              // 重新开始计数
              currentConsecutive = 1;
            }
          }
          
          previousDate = currentDate;
          maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
        }
      }
      
      this.userStats.maxConsecutiveDays = maxConsecutive;
    },
    // 获取用户难度统计
    async fetchUserDifficultyStats() {
      try {
        const userId = localStorage.getItem('userId');
        if (!userId) {
          this.showMessage('error', '用户未登录');
          return;
        }

        const response = await axios({
          method: 'get',
          url: baseURL + `/CodeQuestion-service/problems/getUserDifficultyStats/${userId}`
        });

        if (response.data.result === 'success') {
          const stats = response.data.difficultyStats || [];
          
          // 将统计数据映射到技能数组
          const difficultyMap = {
            'EASY': '简单',
            'MEDIUM': '中等',
            'HARD': '困难'
          };
          
          // 重置技能值
          this.skills = [
            { name: '简单', value: 0 },
            { name: '中等', value: 0 },
            { name: '困难', value: 0 }
          ];
          
          // 更新技能值
          stats.forEach(stat => {
            const difficulty = difficultyMap[stat.difficulty] || stat.difficulty;
            const count = parseInt(stat.count) || 0;
            
            const skill = this.skills.find(s => s.name === difficulty);
            if (skill) {
              skill.value = count;
            }
          });
          
        } else {
          console.error('获取用户难度统计失败：', response.data.message);
        }
      } catch (error) {
        console.error('获取用户难度统计失败:', error);
      }
    },
    // 计算进度条宽度的函数
    calculateProgressWidth(value) {
      // 获取所有技能的最大值
      const maxValue = Math.max(...this.skills.map(s => s.value), 1); // 最小为1，避免除0
      
      // 如果最大值小于10，则让进度条显得更明显一些
      if (maxValue < 10) {
        return value * 10; // 最高达到100%
      }
      
      // 根据最大值计算百分比，最高100%
      return (value / maxValue) * 100;
    }
  },
  async created() {
    // 确保在获取用户信息之前已经设置了有效的 messageType
    this.messageType = 'info';
    this.loading = true; // 初始化时设置loading为true
    try {
      // 先获取用户基本信息
      await this.fetchUserInfo();
      // 获取完用户信息后再获取其他数据
      this.fetchSubmissions();
      this.fetchUserActivityHistory();
      this.fetchUserDifficultyStats();
    } catch (error) {
      console.error('初始化数据失败:', error);
      this.showMessage('error', '加载数据失败，请稍后重试');
    } finally {
      this.loading = false; // 无论成功或失败，都将loading设为false
    }
  }
}
</script>

<style scoped>
.profile {
  min-height: 100vh;
  background: #f0f7ff;
}

.main-content {
  margin-left: 60px;
  padding: 20px;
}

/* 个人信息卡片样式 */
.profile-header {
  margin-bottom: 24px;
}

.profile-card {
  background: white;
  border-radius: 10px;
  padding: 30px;
  display: flex;
  align-items: center;
  position: relative;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
  border: 1px solid #e8f4ff;
}

.profile-avatar {
  position: relative;
  width: 120px;
  height: 120px;
  margin-right: 30px;
  transition: transform 0.3s ease;
}

.profile-avatar:hover {
  transform: scale(1.05);
}

.profile-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #fff;
  box-shadow: 0 0 20px rgba(52, 152, 219, 0.2);
  transition: all 0.3s ease;
}

.profile-avatar:hover img {
  box-shadow: 0 0 25px rgba(52, 152, 219, 0.3);
}

.edit-avatar {
  position: absolute;
  right: 0;
  bottom: 0;
  background: #3498db;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  border: 3px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  opacity: 0.9;
  transform: scale(0.9);
}

.profile-avatar:hover .edit-avatar {
  opacity: 1;
  transform: scale(1);
  background: #2980b9;
}

.edit-avatar i {
  font-size: 16px;
  transition: transform 0.3s ease;
}

.edit-avatar:hover i {
  transform: scale(1.1);
}

.profile-info {
  flex: 1;
}

.profile-info h2 {
  color: #2c3e50;
  margin-bottom: 8px;
}

.profile-info .bio {
  color: #5b7b9a;
  margin-bottom: 20px;
}

.stats {
  display: flex;
  gap: 40px;
}

.stat-item {
  text-align: center;
}

.stat-item .number {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #3498db;
}

.stat-item .label {
  color: #5b7b9a;
  font-size: 14px;
}

.edit-profile {
  position: absolute;
  right: 30px;
  top: 30px;
  padding: 8px 16px;
  background: #e8f4ff;
  border: none;
  border-radius: 20px;
  color: #3498db;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.edit-profile:hover {
  background: #d0e8ff;
}

/* 详细信息区域样式 */
.profile-details {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
}

.section-card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
  border: 1px solid #e8f4ff;
}

.section-card h3 {
  color: #2c3e50;
  font-size: 18px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 提交记录样式 */
.submission-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 8px;
  background: #f8faff;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.submission-item:hover {
  transform: translateX(4px);
  background: #f0f7ff;
}

.status {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.status i {
  color: white;
  font-size: 12px;
}

.submission-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.problem-name {
  color: #2c3e50;
  font-weight: 500;
}

.difficulty-tag {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: white;
  font-weight: 500;
}

.time {
  color: #7f8c8d;
  font-size: 14px;
  margin-left: 12px;
}

.submission-item:last-child {
  margin-bottom: 0;
}

/* 能力分析样式 */
.skill-item {
  margin-bottom: 16px;
}

.skill-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.skill-name {
  color: #2c3e50;
}

.skill-value {
  color: #5b7b9a;
}

.skill-bar {
  height: 6px;
  background: #e8f4ff;
  border-radius: 3px;
}

.skill-progress {
  height: 100%;
  background: #3498db;
  border-radius: 3px;
  transition: width 0.3s ease;
}

/* 日历样式 */
.calendar-container {
  height: 180px;
  width: 100%;
}

.calendar-chart {
  height: 100%;
  width: 100%;
}

/* 保持浅色主题 */
@media (prefers-color-scheme: dark) {
  .profile {
    background: #f0f7ff;
  }
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  border-radius: 15px;
  width: 90%;
  max-width: 600px;
  max-height: 85vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.dialog-header {
  background: #f8faff;
  padding: 20px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e8f4ff;
}

.dialog-header h2 {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 20px;
  color: #2c3e50;
}

.dialog-body {
  padding: 30px;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e8f4ff;
}

.form-section:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.form-section h3 {
  color: #3498db;
  font-size: 16px;
  margin-bottom: 20px;
  font-weight: 500;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #5b7b9a;
  font-weight: normal;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #e8f4ff;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  box-sizing: border-box;
  max-width: 100%;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
  outline: none;
}

.change-password-btn {
  width: 100%;
  padding: 12px;
  background: #f8faff;
  color: #3498db;
  border: 1px solid #e8f4ff;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.change-password-btn:hover {
  background: #e8f4ff;
  transform: translateY(-1px);
}

.change-password-btn i {
  font-size: 16px;
}

.form-actions {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e8f4ff;
  display: flex;
  justify-content: flex-end;
  gap: 15px;
}

.cancel-btn,
.submit-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: #f8faff;
  color: #5b7b9a;
  border: 1px solid #e8f4ff;
}

.submit-btn {
  background: #3498db;
  color: white;
  border: none;
}

.cancel-btn:hover {
  background: #e8f4ff;
}

.submit-btn:hover {
  background: #2980b9;
}

.hidden {
  display: none;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  position: relative;
  overflow: hidden;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
}

.avatar-preview:hover .avatar-overlay {
  opacity: 1;
}

.user-meta {
  display: flex;
  gap: 20px;
  margin: 8px 0;
  color: #5b7b9a;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.meta-item i {
  color: #3498db;
}

.close-btn {
  background: transparent;
  border: none;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #5b7b9a;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: #e8f4ff;
  color: #3498db;
}

.calendar-wrapper {
  width: 100%;
  overflow: hidden;
}

.message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 10px 20px;
  border-radius: 4px;
  color: white;
  z-index: 1000;
}

.message.info {
  background-color: #42b983;
}

.message.error {
  background-color: #ff4757;
}

@media (max-width: 768px) {
  profile-content {
    flex-direction: column;
  }
  
  .profile-left, .profile-right {
    width: 100%;
  }
}

/* 加载动画样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
  margin-left: 60px; /* 与侧边栏宽度一致 */
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-spinner i {
  font-size: 48px;
  color: #3498db;
  margin-bottom: 16px;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: #3498db;
  font-size: 18px;
  font-weight: 500;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 